package com.mfy.controller;


import com.mfy.entity.Category;
import com.mfy.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 分类 前端控制器
 * </p>
 *
 * @author mfy
 * @since 2023-05-09
 */
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private ICategoryService categoryService;
    @GetMapping("/categories")
    public List<Category> selectCategories(){
        return categoryService.selectFirstAndSecondCategory();
    }
    @GetMapping("/selectById/{id}")
    public Category selectById(@PathVariable Integer id){
        return categoryService.getById(id);
    }
    @PatchMapping("/category/{id}")
    public Category updateCategory(@PathVariable("id") int id, @RequestBody Category category){
        category.setId(id);
        category.setUpdatedAt(LocalDateTime.now());
        categoryService.updateById(category);
        return category;
    }
    @PostMapping("/category")
    public Category add(@RequestBody Category category){
        category.setCreatedAt(LocalDateTime.now());
        category.setUpdatedAt(LocalDateTime.now());
        categoryService.save(category);
        return category;
    }
    @DeleteMapping("/category/{id}")
    public void delete(@PathVariable("id") int id){
        try{
            categoryService.removeById(id);
        }catch (Exception e){
            throw new RuntimeException("删除失败");
        }
    }

}

